//
//  HSWebViewController.swift
//  33web
//
//  Created by 宋海胜 on 2020/11/25.
//

import UIKit
import WebKit
import SwiftWeb
import MapKit

import RxSwift
import RxAlamofire
import HandyJSON

enum JsMethod {
    case passGPSInfo
    case passVersion
    case passVoiceContent
    case passPayResult
    case passScanResult
}

// 自定义编辑
class HSWebViewController: BaseWebViewController {
    public var backClosure: ((Int) -> Void)?
    fileprivate var location = LocationManager()
    fileprivate var isOnece = false
    fileprivate var configManager = Tool()
    fileprivate var backImgView = UIImageView()
    fileprivate var urlInputView: InputView!
    public var canAllButUpsideDown = false
    let disposeBag = DisposeBag()
  
    deinit {
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "getGPSInfo")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "saveUnreadMsgCnt")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "getVersion")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "passVideoParams")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "leaveVideoPage")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "startVoice")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "stopVoice")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toMiniProgram")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toGaodeApp")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toPay")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toShare")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "toDownLoad")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "saveImage")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "loginOut")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "webGoBack")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "webShangyiji")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "creditCard")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "mobileBank")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "bankPdf")
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "startScan")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.webView.frame = CGRect(x: 0, y: kStatusBarHeight , width: kScreenWidth, height: kScreenHeight - kStatusBarHeight)
        // 启动图复制图片、web未加载完成时覆盖页面
//        self.backImgView = self.configManager.getLanuchboardImage()
//        self.backImgView.frame = self.view.bounds
//        self.view.addSubview(self.backImgView)
        // 顶部状态栏高度问题解决
        self.configManager.topMangain(webView: webView, vc: self)
        // 网络判断，重新加载网页
        judgeNetwork()
        // 经纬度
        location.locationProtocol = self

//        #if DEBUG // 判断是否在测试环境下
//        // 输入框
        urlInputView = InputView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 100), currentVC: self)
//        view.addSubview(urlInputView)
//        #else
//        #endif
        
//        VersionCheck.hasUpdateVersion(self, disposeBag)
    }
    
    override func injectSwiftMethod(_ config: WKWebViewConfiguration) {
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "getGPSInfo")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "saveUnreadMsgCnt")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "getVersion")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "passVideoParams")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "leaveVideoPage")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "startVoice")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "stopVoice")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toMiniProgram")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toGaodeApp")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toPay")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toShare")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "toDownLoad")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "saveImage")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "loginOut")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "webShangyiji")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "webGoBack")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "creditCard")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "mobileBank")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "bankPdf")
        config.userContentController.add(WeakScriptMessageDelegate(scriptDelegate: self), name: "startScan")
    }
    
    override func jsAction() {
        
    }
    
    // 在viewDidLoad中模态不行，此时页面还没加载完成
    fileprivate func judgeNetwork() {
        self.loadWeb()
        let myAppdelegate = UIApplication.shared.delegate as! AppDelegate
        myAppdelegate.networkAuthStatus(stateClosure: {[weak self] state in
            if let `self` = self {
                if state {
                    DispatchQueue.main.async {
//                        HUDUtil.showHud()
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        DispatchQueue.main.async {
                            HUDUtil.hideHud()
                        }
                        self.loadWeb()
                    }
                }
            }
        })
    }
    
    fileprivate func jsAction(param: String, type: JsMethod) {
        
        var javascript: String = ""
        
        switch type {
            
        case .passGPSInfo:
            javascript = "javascript:passGPSInfo(\"\(param)\")"
            
        case .passVersion:
            javascript = "javascript:passVersion(\"\(param)\")"
            
        case .passVoiceContent:
            javascript = "javascript:passVoiceContent(\"\(param)\")"
            
        case .passPayResult:
            javascript = "javascript:payResult(\"\(param)\")"
        case .passScanResult:
            javascript = "javascript:scanCallback(\"\(param)\")"
        }
        self.webView.evaluateJavaScript(javascript) { (res, error) in
            print("swift向js传值\n  param: \(param)\n  response: \(res ?? "nil")\n  error: \(error?.localizedDescription ?? "nil")")
        }
    }
    
    override func swiftAction(_ name: String, _ body: Dictionary<String, Any>) {
        
        switch name {
        case "webGoBack":
            if webView.canGoBack {
                webView.goBack()
            }
        case "webShangyiji":
            if webView.canGoBack {
                webView.goBack()
            }
        case "loginOut":
            self.backClosure?(0)
            self.navigationController?.popViewController(animated: false)
            
        case "getGPSInfo":
            gpsService()
            
        case "saveUnreadMsgCnt":
            let num = body["notReadNum"] as! NSNumber
            UIApplication.shared.applicationIconBadgeNumber = num.intValue > 99 ? 99 : num.intValue
            
        case "getVersion":
            let infoDic = Bundle.main.infoDictionary
            let appVersion = infoDic!["CFBundleShortVersionString"] as! String
            jsAction(param: appVersion, type: .passVersion)


        case "toGaodeApp":
            Tool.routePlanning(body)

      
        case "toDownLoad":
            let url = body["url"] as? String ?? ""
            UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil)
            
        case "callSomeOne":
            let phoneNum = body["phoneNum"] as? String ?? ""
            self.configManager.callSomeOne(phoneNum)
        case "startScan":
            // 需要导入 LBXScan 和 AVFoundation 框架
            
            
                    // 创建扫码界面（默认类型是 .all，可扫码和条形码）
                    let scanVC = ScanManager.shared.createScanViewController(
                        type: .all,  // 只扫描二维码
                        result: { [weak self] result in
                            // 扫码成功回调
                            self?.dismiss(animated: true) {
                                self?.jsAction(param: result, type: .passScanResult)
                            }
//                            self?.handleScanResult(result)
                        },
                        cancel: { [weak self] in
                            // 用户取消扫码
                            self?.dismiss(animated: true)
                            print("Scan cancelled")
                        }
                    )
                    
                    // 以模态方式呈现（如果是导航控制器，可以用 pushViewController）
                    let navController = UINavigationController(rootViewController: scanVC)
                    navController.modalPresentationStyle = .fullScreen
                    present(navController, animated: true)
                
        default:
            break
        }
    }
    
    private func handleScanResult(_ result: String) {
        print("结果为: \(result)")
        dismiss(animated: true) {
            self.jsAction(param: result, type: .passScanResult)

     
            // 显示结果
            //             let alert = UIAlertController(
            //                 title: "Scan Result",
            //                 message: result,
            //                 preferredStyle: .alert
            //             )
            //             alert.addAction(UIAlertAction(title: "OK", style: .default))
            //             self.present(alert, animated: true)
        }
    }
    
    override func getH5Url(_ url: String) {
        
        if (url.contains("tel://")) {
            let phoneUrl = url.components(separatedBy: "tel://").last
            self.configManager.callSomeOne(phoneUrl!)
        }
    }
    
    override func loadSuccess() {
        
        UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: {
            self.backImgView.alpha = 0
        }) { (finish) in
            self.backImgView.isHidden = true
        }
    }
    
    override func loadFail() {
        backImgView.isHidden = false
        self.configManager.alertToReload(self) {
            self.loadWeb()
        }
    }
    
    // 定位
    fileprivate func gpsService() {
        
        //只获取一次
        isOnece = true
        self.location.startLocation()
    }
    


    
    func voiceContent(content: String) {
        self.jsAction(param: content, type: .passVoiceContent)
    }
    
    func payResult() {
        self.jsAction(param: "", type: .passPayResult)
    }
    
    
    
    
    
    
}

extension HSWebViewController: LocationProtocol {
    func getLocationSuccess(_ area: String, _ locality: String, _ subLocality: String, _ thoroughfare: String, _ name: String) {
        
    }
    
    
    func getGPSAuthorizationFailure() {
        let alert = UIAlertController(title: "提示", message: "请打开定位，以便获取您的位置信息", preferredStyle: .alert)
                     
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
                     
        self.present(alert, animated: true, completion: nil)
    }
    
    func getGPSSuccess(latitude: Double, longitude: Double) {
        location.stopLocation()
        if (self.isOnece) {
            print("lng: \(longitude) lat: \(latitude)")
            let param = "\(longitude),\(latitude)"
            self.jsAction(param: param, type: .passGPSInfo)
            self.isOnece = false
        }
    }
    
    func getGPSFailure(error: Error) {
        self.isOnece = false
        print("getMoLocation error: \(error.localizedDescription)")
        if (!self.isOnece) {
            location.stopLocation()
        }
    }
}
